//
//  RegionModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/3/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation


final class RegionModel {
    
    var cities: [City] = []
    var options: [[String : Any]] = [] {
        didSet {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "regionUpdate"), object: nil, userInfo: ["data": options, "error": false])
        }
    }
    
    func loadData () {
        let backend = Backend()
        let url = Request(base: .advert).getUrl(path: "geo/cities")
        let request = URLRequest(url: url)
        
        backend.fetchFromBackend(for: Response<[City]>.self, request: request, statusCode: 200) { (result) in
            switch result {
            case .failure(let error):
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "regionUpdate"), object: nil, userInfo: ["error": true, "data": error])
            case .success(let cities):
                self.cities = cities.results
                self.toVisualFormat(data: cities.results)
            }
        }
    }
}

extension RegionModel {
    private func toVisualFormat (data: [City]) {
        var output:[[String: Any]] = []
        for city in data {
            if let index = output.firstIndex(where: { $0["name"] as! String == city.region.name }) {
                if var items = output[index]["items"] as? [[String: Any]] {
                    items.append(["name": city.name])
                }
            } else {
                output.append([
                    "name": city.region.name,
                    "items": [["name": city.name]]
                ])
            }
        }
        let _data = [
            [
                "name": "Все регионы",
                "items": output
            ]
        ]
        self.options = _data
    }
    
    func toCityFormat (options: [String: [OptionViewModel]]) -> [City] {
        var output: [City] = []
        for title in options.keys {
            for optionItem in options[title]! {
                if let items = optionItem.option.items {
                    for item in items {
                        if (item.isSelected ?? false) {
                            let city = cities.first {
                                $0.name == item.name
                            }
                            if city != nil {
                                output.append(city!)
                            }
                        }
                    }
                }
            }
        }
        return output
    }
}

